package com.westos.todo.service;

import java.util.ArrayList;
import java.util.List;

import org.apache.ibatis.session.SqlSession;

import com.westos.todo.dao.TodoDao;
import com.westos.todo.entity.Todo;
import com.westos.todo.entity.TodoClass;
import com.westos.todo.page.TodoClassVO;
import com.westos.todo.util.MybatisUtil;

public class TodoServiceImpl implements TodoService{

	@Override
	public List<TodoClassVO> listtoclasses(Integer parentid) {
		SqlSession sqlsession=MybatisUtil.getInstance().getSqlSessionFactory().openSession();
		
		TodoDao dao=sqlsession.getMapper(TodoDao.class);
		List<TodoClassVO> result=new ArrayList<>();
		
		try {
			List<TodoClass> root=dao.listtodoclassByParentid(parentid);
			for(TodoClass tc:root){
				TodoClassVO todoClassVO=new TodoClassVO();
				todoClassVO.setTodoclass(tc);
				todoClassVO.setTodos(dao.listtodoByClassid(tc.getId()));
				todoClassVO.setTodoclassvoList(listtoclasses(tc.getId()));
				result.add(todoClassVO);
			}
			return result;
		} finally{
			sqlsession.close();
		}
	}

	@Override
	public boolean saveTodoClass(TodoClass todoClass) {
		SqlSession sqlsession=MybatisUtil.getInstance().getSqlSessionFactory().openSession();
		TodoDao dao=sqlsession.getMapper(TodoDao.class);
		int result=0;
		try {
			result=dao.saveTodoClass(todoClass);
			sqlsession.commit();
			//System.out.println(todoClassName);
		} finally{
			sqlsession.close();
		}
		return result>0;
	}

	@Override
	public boolean saveTodo(Todo todo){
		SqlSession sqlsession=MybatisUtil.getInstance().getSqlSessionFactory().openSession();
		TodoDao dao=sqlsession.getMapper(TodoDao.class);
		int result=0;
		try {
			result=dao.saveTodo(todo);
			sqlsession.commit();
		} finally{
			sqlsession.close();
		}
		
		return result>0;
	}

	@Override
	public Boolean updateTodo(Integer id) {
		SqlSession sqlsession=MybatisUtil.getInstance().getSqlSessionFactory().openSession();
		TodoDao dao=sqlsession.getMapper(TodoDao.class);
		int result=0;
		try {
			result=dao.updateTodoState(id);
			sqlsession.commit();
		} finally{
			sqlsession.close();
		}
		
		return result>0;
	}

	@Override
	public boolean removeTodo(Integer id) {
		SqlSession sqlsession=MybatisUtil.getInstance().getSqlSessionFactory().openSession();
		TodoDao dao=sqlsession.getMapper(TodoDao.class);
		int result=0;
		
		try {
			result=dao.removeTodo(id);
			sqlsession.commit();
		} finally{
			sqlsession.close();
		}
		
		return result>0;
	}

	
	
	
}
